package com.chare.Controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chare.pojo.*;
import com.chare.service.IMenuRoleService;
import com.chare.service.IMenuService;
import com.chare.service.IRoleService;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author shi
 * @since 2022-06-17
 */
@RestController
@RequestMapping("/system/basic/permiss")
public class RoleController {
@Autowired
private IRoleService roleService;
@Autowired
private IMenuService menuService;
@Autowired
private IMenuRoleService menuRoleService;

@ApiModelProperty("获取全部角色")
@GetMapping("/")
public List<Role> getall()
{
    return roleService.list();

}
    @ApiModelProperty("添加角色")
    @PostMapping("/")
    public RespBean add(@RequestBody Role role)
    {
        if(!role.getName().startsWith("ROLE_"))  //startsWith 用来比较字符串是否以指定的前缀出现
        {
           role.setName("ROLE_"+role.getName());
        }
        if(roleService.save(role))
        {
            return  RespBean.success("添加成功");
        }else {
            return  RespBean.error("添加失败");
        }
    }
    @ApiModelProperty("删除角色")
    @DeleteMapping("/{id}")
    public  RespBean delete(@PathVariable Integer id)
    {
        if(roleService.removeById(id))
        {
            return RespBean.success("删除成功");
        }
        else {
            return RespBean.error("删除失败");
        }

    }
    @ApiModelProperty("查询所有菜单")
    @GetMapping("/menus")
    public  List<Menu> getallMenus()
    {
      return   menuService.getAllMenus();
    }
    @ApiModelProperty("根据角色id查询菜单")
    @GetMapping("/mid/{rid}")
    public List<Integer> getMenusByRoleId(@PathVariable Integer rid)
    {
        return menuRoleService.list(new QueryWrapper<MenuRole>().eq("rid",rid)).stream().map(MenuRole::getMid).collect(Collectors.toList());
    }
    @ApiModelProperty("更新角色相对应的菜单列表")
    @PutMapping("/")
    public  RespBean updateMenus(Integer rid,Integer [] mids)
    {
        return menuRoleService.updateMenus(rid,mids);
    }

}
